# -*- coding: utf-8 -*-
import ast
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address
from common.utils.qr import make_code

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '62115413': {
        # np付 银联扫码 1.7%（？）dwc
        # np付 银联快捷 1.4%（？）dwc
        'API_KEY': '880bfa3a-edd0-40a0-88d7-03b1665792a0',
        'gateway': 'https://fin.newpingon.com/sdk/json.do',
        'query_gateway': 'https://fin.newpingon.com/sdk/json.do',
    },
    '62010002': {
        # np付 银联扫码 1.7%（？）dwc
        # np付 银联快捷 1.4%（？）dwc
        'API_KEY': '12345678-9388-11de-b73f-0f19974d6b20',
        'gateway': 'https://fin.newpingon.com/sdk/json.do',
        'query_gateway': 'https://fin.newpingon.com/sdk/json.do',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


# notify_url + order_id + order_name + price + return_url + token + type + uid
def generate_sign(parameter, key):
    s = '{}&{}'.format(parameter, key)
    _LOGGER.info('nppay sign str: %s', s)
    return _gen_sign(s)


# order_id + order_uid + price + transaction_id + token
def generate_notify_sign(parameter, key):
    s = '{}{}{}{}{}'.format(parameter['order_id'], parameter['order_uid'],
                            parameter['price'], parameter['transaction_id'],
                            key)
    _LOGGER.info('nppay notify sign str: %s', s)
    return _gen_sign(s)


def verify_sign(params, key, back_sign):
    calculated_sign = generate_sign(params, key)
    if back_sign.upper() != calculated_sign.upper():
        _LOGGER.info("nppay sign: %s, calculated sign: %s", back_sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 01:网银支付模式
# 02:H5支付模式
# 03:快捷支付模式
# 04:扫码支付模式
def _get_pay_type(service):
    if service == 'unionpay_quick':
        return '03'
    elif service == 'unionpay_scan':
        return '04'
    return '04'


# "银行代号
# payMode=01,02,04时,须使用以下银行代号
# WECHAT (微信)
# ALIPAY (支付宝)
# QQW (QQ钱包)
# JD(京东)
# CUP(中国银联)"
def _get_bank_id(service):
    if service == 'unionpay_quick':
        return ''
    elif service == 'unionpay_scan':
        return 'CUP'
    return 'CUP'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    tradeData = {
        'merId': str(app_id),
        'orderId': str(pay.id),
        'goods': 'charge',
        'amount': '%.2f' % pay_amount,
        # 'expTime': local_now().strftime('%Y-%m-%d %H:%M:%S'),
        'notifyUrl': '{}/pay/api/{}/nppay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
        'pageUrl': '{}/pay/api/{}/nppay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'payMode': _get_pay_type(service),
        'payBankId': _get_bank_id(service),
        'payClient': 'WAP',
        'userId': str(pay.user_id),
        'clientIp': str(_get_device_ip(info)),
        'creditType': '2',
    }
    parameter_dict = OrderedDict((
        ('tradeId', 'payGateway'),
        ('ver', '1.0'),
        ('tradeData', str(tradeData).encode('utf8')),
    ))
    parameter_dict['tradeSign'] = generate_sign(tradeData, api_key)
    _LOGGER.info("nppay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    url = _get_gateway(app_id) + '?tradeId=' + parameter_dict['tradeId'] + '&ver=1.0&tradeData=' + str(
        parameter_dict['tradeData']) + '&tradeSign=' + parameter_dict['tradeSign']
    response = requests.post(url, headers=headers, timeout=5)
    _LOGGER.info("url is: %s", url)
    # response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("nppay create rsp data: %s", response.text)
    data = json.loads(response.text)
    backData = ast.literal_eval(response.text.encode("utf-8"))['backData']
    verify_sign(str(backData).replace(" ", "").replace("'", "\""), api_key, data['backSign'])
    _LOGGER.info("backData['payUrl'] is: %s", backData['payUrl'])
    _LOGGER.info("data payUrl is: %s", data['backData']['payUrl'])
    if service == 'unionpay_scan':
        template_data = {'base64_img': make_code(backData['payUrl']), 'amount': pay_amount,
                         'order_id': str(pay.id), 'due_time': int(time.time()) + 180}
        t = get_template('cloud_flash_nppay.html')

        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("nppay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("notify body is: %s", request.body)

    data = dict(request.POST.iteritems())
    _LOGGER.info("nppay notify data: %s", data)
    verify_sign(data['tradeData'], api_key, data['tradeSign'])

    tradeData = ast.literal_eval(data['tradeData'].encode("utf-8"))
    pay_id = tradeData['orderId']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('nppay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(tradeData['result'])
    trade_no = str(tradeData['payOrderId'])
    total_fee = float(tradeData['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)
    # S：成功,F：失败,U：交易不确定
    if trade_status == 'S':
        _LOGGER.info('nppay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    tradeData = {
        'merId': str(app_id),
        'orderId': str(pay_id)
    }
    parameter_dict = OrderedDict((
        ('tradeId', 'payOrderQuery'),
        ('ver', '1.0'),
        ('tradeData', str(tradeData).encode('utf8')),
    ))
    parameter_dict['tradeSign'] = generate_sign(tradeData, api_key)
    _LOGGER.info('nppay query data, %s', json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('nppay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['backData']
        mch_id = pay_order.mch_id
        trade_status = str(data['result'])
        total_fee = float(data['amount'])
        trade_no = str(data['orderId'])

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # S：成功,F：失败,U：交易不确定
        if trade_status == 'S':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('nppay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
